import pygame

def render_with_border(text, font, fg_color, bg_color, border_color, border_width=1, colorkey = -1):
    """Write bordered text to a surface.
    """
    # Create the target surface large enough for the text and border. Set its
    # colorkey.
    w,h = font.size(text)
    surf = pygame.surface.Surface((w+2*border_width, h+2*border_width))
    surf.fill(bg_color)
    if colorkey == -1:
        colorkey = bg_color
    surf.set_colorkey(colorkey, pygame.RLEACCEL)
    # Render the text in border_color, at various offsets to fake a border.
    tmp = font.render(text, 1, border_color)
    dirs = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]
    pos = 1+border_width, 1+border_width
    for dx,dy in dirs:
        surf.blit(tmp, (pos[0]+dx*border_width, pos[1]+dy*border_width))
    # Now render the filled text, in the fg_color.
    tmp = font.render(text, 1, fg_color)
    surf.blit(tmp, pos)
    return surf
